
(function($) {

	var ifrwin=null;
	var ifrdoc=null;
	var range_ie = null;
	$.fn.RTE = function(content,imgpath) {
			//alert (content);
			var ta = this;
			var ifr=null;
			addBar(ta, imgpath);
			if (!$("ul.rte_ul")) return
			addEditor(ta);
			ifr = $("iframe");
			if (ifr[0]) {
				ifrwin = ifr[0].contentWindow;
				ifrdoc = ifrwin.document;
				// document is set editable
				ifrdoc.designMode = "on";
				ifrdoc.contentEditable = true;
				ifrdoc.open(); // open stream
				ifrdoc.writeln(CR2BR(content));
				ifrdoc.close();
			} else {return;}
			bindCommand();
		//})
	};

	// Convert \r\n, \r to <br>
	// Textarea value - IE: CR is treated as \r\n. FF/Safari CR is treated as \n
	function CR2BR(s) {
		if (/\r\n|\n/g.test(s))
			return s.replace(/\r\n|\n/g, "<br />");
		return s;
	}
	function addEditor(taObj) {
		if ($("#rte_box iframe")[0]) return;
		if (!$("#rte_box")[0]) {
			taObj.before($("<div id='rte_box' class='rte_box'></div>"));
		}
		$("<iframe><html><body></body></html></iframe>").appendTo("#rte_box");
		if (!$.browser.msie) addCSS($("#rte_box"));
		//return $("iframe");
	}
	function addBar(taObj,imgpath) {
		var bar;
		var bar_arr=new Array();
		if ($(".bar")[0]) {
			bar=$(".bar");
		} else {
			bar=$("<div class='bar'></div>").insertBefore(taObj);
		}
		//if (!bar.find(".bar_ul")) {
			bar_arr.push('<ul class="bar_ul"><li><a title="bold" class="command common" st= "bold" href="javascript: void(0)"><img height="20" width="20" src='+imgpath+'bold.gif></a></li>');
			bar_arr.push('<li><a title="underline" class="command common" st="underline" href="javascript: void(0)"><img height="20" width="20" src='+imgpath+'underline.gif></a></li>');
			bar_arr.push('<li><a title="italic" class="command common" st="italic" href="javascript: void(0)"><img height="20" width="20" src='+imgpath+'italics.gif></a></li>');
			bar_arr.push('<li><a title="strikethrough" class="command common" st="strikethrough" href="javascript: void(0)"><img height="20" width="20" src='+imgpath+'strikethrough.gif></a></li>');
			bar_arr.push('<li><a title="font color" id="forecolor" class="command common" st="forecolor" href="javascript: void(0)"><img height="20" width="20" src='+imgpath+'forecolor.gif></a></li>');
			bar_arr.push('<li><select id="fontsize" class="command" st="fontsize">');
			bar_arr.push('<option value="">size</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option>');
			bar_arr.push('</select></li>');
			bar_arr.push('<li><a title="createlink" class="command common" st="createlink" href="javascript: void(0)"><img height="20" width="20" src='+imgpath+'insert_hyperlink.gif></a></li>');
			bar_arr.push('<li><a title="remove all format" id="remove_format" class="command" st="removeformat" href="javascript: void(0)"><img height="20" width="20" src='+imgpath+'remove_format.gif></a></li></ul>');
			bar.html(bar_arr.join(""));
		//}
	}
	function stripTags(s) {
		return s.replace(/<\/?[^>]+>/gi, '');
	}
	function addCSS(obj) {
		obj.css({"border-top":"#666666 2px solid","border-left":"#666666 2px solid", "border-bottom":"#CCCCCC 1px solid", "border-right":"#CCCCCC 1px solid"});
	}

	function editText(type, flag, args) {
		//if (!$.browser.msie) ifrdoc.execCommand("styleWithCSS", false, false);
		var flag = !!flag;
		var args = args ? args : null;
		//alert(type+"-"+flag+"-"+args);
		//alert(ifrdoc);
		ifrdoc.execCommand(type, flag, args);
		return ifrwin.getSelection();
	}

	function renderColorPicker(jObj) {
		if ($.browser.msie) {
			var range = ifrdoc.selection.createRange();
			jObj.colorPicker({setBackground:false, ifrWin:ifrwin, ifrRange:range});
		} else {
			jObj.colorPicker({setBackground:false, ifrWin:ifrwin});
		}
		$("#fy_ColorPicker").hover(function(){},hideColorPicker);
	}

	function hideColorPicker(){
		$("#fy_ColorPicker").hide();
	}
	function renderDialog(obj){
		if ($.browser.msie) {//alert(ifrdoc.selection.createRange().text);
			range_ie = ifrdoc.selection.createRange();
		}
		if ($("#hyperlink_dialog")[0] && $("#hyperlink_dialog:hidden")) {
			$("#hyperlink_dialog").show();
			return;
		}
		if (!$("#hyperlink_dialog")[0]) {
			var el = $("<div></div>").appendTo("body")[0];
			el.id="hyperlink_dialog";
			el.style.position = "absolute";
			el.style.height = "50px";
			el.style.width = "200px";
			var offset = obj.offset();
			//alert(offset.left);
			$(el).css({"left":offset.left,"top":offset.top+20});
			$(el).css({"padding-top":"10px","background-color":"#FFFFFF","border":"1px solid #CCCCCC","z-index":99});
			var link_box = ["<ul>"];
			link_box.push("<li><span style='font-size: 10px'>URL:</span><input id='hlink_id' type='text' /></li>");
			link_box.push("<!--li><span>Target:</span>");
			link_box.push("<select id='target_id' name='target_item'>");
			link_box.push(	"<option value=''>no target</option>" +
						"<option value='_blank'>_blank</option>" +
						"<option value='_self'>_self</option>" +
						"<option value='_parent'>_parent</option>" +
						"<option value='_top'>_top</option>"
					)
			link_box.push("</select></li-->");
			link_box.push("<li style='float:right'><span style='margin-right:30px;font-size:10px;'><a id='ok_id' href='javascript:void(0)'>Ok</a></span><span ><a href='javascript:void(0)' id='cancel_id' style='font-size:10px'>Cancel</a></span></li>");
			link_box.push("</ul>");
			//alert(link_box.join(""));
			$(el).append(link_box.join(""));
		}
		
		// binding event for ok/cancel
		$("#ok_id").click(function(){
			var link = $.trim($("#hlink_id").val());
			var st = link? "createlink" : "unlink";
			if ($.browser.msie) {
				var range_now = ifrdoc.selection.createRange();
				range_ie = range_now.text ? range_now : range_ie;
				if (link == "")
					range_ie.execCommand('unlink', false, null);
				else
					range_ie.execCommand('createlink', false, link);
			} else {
				editText(st, false, link);
				//var r = ifrwin.getSelection().getRangeAt(0);
				//alert ($(df).html());
				//r.startContainer();


			}
		$("#hyperlink_dialog").hide();
		});
		$("#cancel_id").click(function(){$("#hyperlink_dialog").hide()});
	}
	
	function bindCommand() {
		//Binding for fontsize command
		$("#fontsize").change(function(){
			var s = $("#fontsize option:selected").val();
			editText("fontsize", false, s);
		});

		$(".common").click(function(){
			var st = $(this).attr("st").toLowerCase();
			if (st == "createlink") {
				renderDialog($(this));
				return;
			} else if (st == "forecolor") {
				renderColorPicker($(this));
				return;
			} else {
				editText(st, false, null);
			}
		});
		$(".command img").hover(
			function(){
				var img = this;
				var src = $(img).attr("src");
				$(img).attr("src",src.replace(/\.gif$/gi, "_on.gif"));
			},
			function(){
				var img = this;
				var src = $(img).attr("src");
				$(img).attr("src", src.replace(/_on\.gif$/gi, ".gif"));
			}
		);

		$("#remove_format").click(function(){
		var new_s = stripTags(ifrdoc.body.innerHTML);
		ifrdoc.body.innerHTML=new_s;
		});
	}

	$("#click_id").click(function(){
		alert(ifrdoc.body.innerHTML);
	});
})(jQuery);



/**
 * Color Picker for jQuery
 *
 * author: feiyu
 * e-mail: feiyu@asgard.cn
 * website: http://feiyu.asgard.cn
 *
 * Version: 1.1.0
 */
(function($) {

	var loc={Top:-1,Left:-1,Width:-1,Height:-1};
	var isOn=false;
	var colorVal = "";

	$.fn.colorPicker=function(vIn) {

		var obj=this;

		if (vIn) {
			if (vIn.constructor != Object) {
				vIn = { setBackground : vIn }
			}
		}
		else {
			vIn = {};
		}
		var opt=setDefaults();

		this.colorVal = "";

		$.extend(opt,vIn);

		$.each(opt,function(n,v) {

			if(v!=false&&n!='align') {
				// Peng
				if (typeof v =='object') {
					opt[n.toLowerCase()] = v;
				} else if (typeof v=='string' || isDOM(v)) {
					opt[n] = $(v);
				}
				else if (v==true) {
					opt[n] = obj;
				}
				else if (!isJQuery(v))
					opt[n] = false;
			}
		});
		if (opt.align.toLowerCase()!='left') opt.align='right';

		var cp = $('#fy_ColorPicker');
		var cf=$('#fy_CP_Frame');
		if (cp.length==0) {
			cp = $('<div id="fy_ColorPicker"></div>');
			cp.css({"position":"absolute","z-index":"100","background-color":"#FFFFFF","border":"1px solid #CCCCCC","padding":"1px","cursor":"pointer","display":"none"});
			var hc = ["FF","CC","99","66","33","00"];
			var i=0,j=0;
			var r,g,b,c;
			var s = new Array();
			s[0] = '<table cellspacing="1" cellpadding="0" style="table-layout:fixed"><tr>';
			for(r=0;r<6;r++) {
				for(g=0;g<6;g++) {
					for(b=0;b<6;b++) {
						c = hc[r] + hc[g] + hc[b];
						if (i%18==0 && i>0) {
							s[j+1] = "</tr><tr>";
							j++;
						}
						s[j+1] = '<td class="color" bgcolor="#'+c+'" height="15" width="15" style="width:15px"></td>';
						i++;
						j++;
					}
				}
			}
			s[j+1] = '</tr><tr><td height="10" colspan="16" id="fy_ColorPicker_Select" style="font-family:Tamoha;font-size:10px;text-align:center;cursor:default;"></td><td class="color" bgcolor="" height="10" colspan="1" title="Empty" align="center" style="font-family:Tamoha;font-size:10px">E</td><td class="color" bgcolor="transparent" height="10" colspan="1" title="Transparent" align="center" style="font-family:Tamoha;font-size:10px">T</td></tr></table>';
			cp.html(s.join(''));
			cp.appendTo('body');

			if($.browser.msie&&cf.length==0) {
				cf=$('<iframe scrolling="no" frameborder="0" style="position:absolute;z-index:99;display:none" id="fy_CP_Frame"></iframe>');
				cf.appendTo('body');
			}
		}


		var tl=GetLoc(obj[0]);

		if (cp.is(':visible')&&tl.Top==loc.Top&&tl.Left==loc.Left) {
			cp.hide();
			if($.browser.msie) cf.hide();
		}
		else {
			loc = tl;

			cp.css({"left":tl.Left+(opt.align.toLowerCase()!='left'?tl.Width:0)+"px","top":(tl.Top+tl.Height)+"px"});
			tl = GetLoc(cp[0]);
			cf.css({"left":tl.Left,"top":tl.Top,"width":tl.Width,"height":tl.Height});
			cp.show();
			if($.browser.msie) cf.show();


			$(document).click(function(e) {
				var t=$.browser.msie?window.event.srcElement:e.target;
				if(!compareObj(t) && $('#fy_ColorPicker').is(':visible') && t.id!="fy_ColorPicker" && $(t).parents("#fy_ColorPicker").length==0) {
					$("#fy_ColorPicker").hide();
					if($.browser.msie) cf.hide();
				}
			});

			$('.color',cp).unbind("mouseover").unbind("click").mouseover(function() {
				setSelect(this.bgColor.toUpperCase());
			}).click(function() {
				colorVal = this.bgColor.toUpperCase();
				setColorValue(this.bgColor.toUpperCase(),opt);

				// Hook function for changing forecolor. 
				if (opt["ifrwin"]) {
					var ifrwin = opt["ifrwin"];
					if (opt["ifrrange"] && (opt["ifrrange"].text!="")) {
						var range = opt["ifrrange"];
						//range.findText("a");
						range.select();
						ifrwin.focus();
						range.execCommand("forecolor", false, colorVal);
					} else {
						ifrwin.document.execCommand("forecolor", false, colorVal);
					}
				}
				//opt["ifrRange"].execCommand("forecolor", false, colorVal);
			});
		}
		function getC(){return colorVal;}
		return getC;
	};

	function compareObj(obj) {
		//$(obj[0].nodeName).index(obj[0])==$(obj[0].nodeName).index(t)
		var oloc=GetLoc(obj);
		return loc.Top==oloc.Top&&loc.Left==oloc.Left&&loc.Width==oloc.Width&&loc.Height==oloc.Height;
	}

	function setDefaults() {
		return {
		setBackground: true,
		setValue: false,
		setColor: false,
		setText: false,
		align: 'left',
		ifrWin: null,
		ifrRange: null
		}
	}

	function setColorValue(v,vIn) {
		colorVal = v;
		var v=v=='TRANSPARENT'?'transparent':v;
		$('#fy_ColorPicker').hide();
		if(vIn.setBackground!=false) {
			vIn.setBackground.css('background-color',v);
		}
		if(vIn.setColor!=false) {
			vIn.setColor.css('color',v);
		}
		if(vIn.setValue!=false) {
			vIn.setValue.val(v);
		}
		if(vIn.setText!=false) {
			vIn.setText.text(v);
		}
	}

	function GetLoc(element) {
		if ( arguments.length != 1 || element == null ) { 
			return null;
		} 
		var offsetTop = element.offsetTop; 
		var offsetLeft = element.offsetLeft; 
		var offsetWidth = element.offsetWidth; 
		var offsetHeight = element.offsetHeight; 
		while( element = element.offsetParent ) { 
			offsetTop += element.offsetTop;
			offsetLeft += element.offsetLeft;
		}
		return { Top: offsetTop, Left: offsetLeft, Width: offsetWidth, Height: offsetHeight };
	}

	function setSelect(v) {
		var v=v=='TRANSPARENT'?'transparent':v;
		$("#fy_ColorPicker_Select").css('background-color',v).text(v);
	}

	function isDOM(vIn) {
		return (typeof vIn=='object' && !!vIn.nodeName);
	}

	function isJQuery(vIn) {
		return (typeof vIn=='object' && !!vIn.attr);
	}

	// Add Get method
	function getColorValue() {
		return colorVal;
	}
})(jQuery);